package com.phs.main.common.documents;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
import com.phs.main.vo.ConvertToVO;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * 将LocalDateTime 转成Date
 */
public class ExcelUtil implements Converter<LocalDateTime> {

	public static void getExcel(Class<?> clazz, List<?> result, String filePath, String sheetName) {
		EasyExcel.write(filePath, clazz)
				.registerConverter(new ExcelUtil())
				.sheet(sheetName)
				.doWrite(result);
	}

	public static void getExcel(Class<?> clazz, List<?> result, String filePath) {
		ExcelUtil.getExcel(clazz, result, filePath, "sheet1");
	}

	public static void getVOExcel(Class<?> clazz, List<?> result, String filePath) {
		EasyExcel.write(filePath, clazz)
				.registerConverter(new ExcelUtil())
				.sheet()
				.doWrite(ConvertToVO.getVOList(result, clazz));
	}

	public static ExcelWriterSheetBuilder downloadExcel(String name, Class<?> clazz, HttpServletResponse response) throws IOException {
		response.setContentType("application/vnd.ms-excel");
		response.setCharacterEncoding("utf-8");
		// 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
		String fileName = URLEncoder.encode(name, "UTF-8");
		response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
		return EasyExcel
				.write(response.getOutputStream(), clazz)
				.registerConverter(new ExcelUtil())
				.sheet();
	}

	@Override
	public Class<LocalDateTime> supportJavaTypeKey() {
		return LocalDateTime.class;
	}

	@Override
	public CellDataTypeEnum supportExcelTypeKey() {
		return CellDataTypeEnum.STRING;
	}

	@Override
	public LocalDateTime convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
		return LocalDateTime.parse(cellData.getStringValue(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
	}

	@Override
	public CellData<?> convertToExcelData(LocalDateTime value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
		return new CellData<>(value.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
	}
}
